package com.ibeetl.admin.aod.service.excel.processor;

import com.ibeetl.admin.aod.util.exception.ImportException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jxls.reader.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class AbstractImportProcessor<T> implements ImportProcessor {

    private final Log log = LogFactory.getLog(this.getClass());

    @Override
    public void process(MultipartFile file, String templatePath) throws Exception {

        if (file.isEmpty()) {
            throw new ImportException("文件为空");
        }
        log.info("正在进行预处理");
        preProcess();
        log.info("预处理结束");

        log.info("正在进行解析文件");
        List<T> dataList = parseFile(file, templatePath);
        log.info("解析文件结束");

        log.info("正在进行后置处理");
        postProcess(dataList);
        log.info("后置处理结束");

    }

    protected List<T> parseFile(MultipartFile file, String templatePath) throws Exception {

        InputStream ins = file.getInputStream();

        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(templatePath);
        XLSReader xlsReader = ReaderBuilder.buildFromXML(inputStream);
        InputStream inputXLS = ins;
        List<T> dataList = new ArrayList<>();
        Map beans = new HashMap();
        beans.put("list", dataList);
        ReaderConfig.getInstance().setSkipErrors(true);
        XLSReadStatus readStatus = xlsReader.read(inputXLS, beans);
        List<XLSReadMessage>  errors = readStatus.getReadMessages();
        if(!errors.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for(XLSReadMessage msg:errors) {
                sb.append(parseXLSReadMessage(msg));
                sb.append(",");
            }
            sb.setLength(sb.length()-1);
            throw new ImportException("解析excel出错:" + sb.toString());
        }
        return dataList;
    }

    protected void postProcess(List<T> dataList) {

    }

    protected void preProcess() {

    }

    /*xlsReader 设计有问题，还需要通过解析msg知道错误位置在哪里*/
    private String parseXLSReadMessage(XLSReadMessage msg) {
        String str = msg.getMessage();
        int start = "Can't read cell ".length();
        int end = str.indexOf("on");
        return str.substring(start,end);
    }

}
